package cn.youdian.web.admin.controller;

import cn.youdian.core.api.JsonResult;
import cn.youdian.core.api.ResultCode;
import cn.youdian.core.api.util.JsonResultUtils;
import cn.youdian.core.util.StringUtils;
import cn.youdian.web.admin.model.LoginModel;
import cn.youdian.web.admin.result.LoginResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * @author K.J
 * @description TODO
 * @date 2021/5/28 16:48
 **/
@RestController
public class LoginController extends BaseController {
    @Autowired
    private HttpSession session;

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @GetMapping("/login")
    public ModelAndView login() {
        ModelAndView view = new ModelAndView("/login/index.html");
        return view;
    }

    @PostMapping("/login/do")
    public JsonResult<LoginResult> doLogin(@RequestBody LoginModel model) {

        JsonResult<LoginResult> jsonResult = new JsonResult<LoginResult>();
        UsernamePasswordToken token = new UsernamePasswordToken(model.getUsername(), model.getPassword());
        try {
            SecurityUtils.getSubject().login(token);
            LoginResult result = new LoginResult();
            result.setSid(StringUtils.random(35));
            jsonResult = JsonResultUtils.ok("登录成功.", result);
        } catch (AuthenticationException e) {
            if (e instanceof UnknownAccountException) {
                jsonResult = JsonResultUtils.fail(ResultCode.FAIL, "用户不存在.");
            } else if (e instanceof LockedAccountException) {
                jsonResult = JsonResultUtils.fail(ResultCode.FAIL, "用户被禁用.");
            } else if (e instanceof IncorrectCredentialsException) {
                jsonResult = JsonResultUtils.fail(ResultCode.FAIL, "用户名或密码错误.");
            } else {
                jsonResult = JsonResultUtils.fail(ResultCode.FAIL, "用户名或密码错误.");
            }
//            return "/login";
        }
//        return "redirect:/";
        return jsonResult;
    }

    @GetMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }
}
